package com.example.permission.myjbm.fragments;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.sinopec.activity.LoginActivity;
import com.example.jbmsuppliers.sinopec.orderaddress.MyAddRessRepair;
import com.example.jbmsuppliers.sinopec.view.DialogLoading;
import com.example.permission.myjbm.adapter.MyFragmentAdapter;
import com.example.permission.myjbm.dao.BaseFgm;
import com.example.permission.myjbm.model.MyFragmentModel;
import com.example.permission.myjbm.net.ReleaseNet;
import com.example.permission.myjbm.utils.DataCache;
import com.example.permission.myjbm.utils.Identifying;
import com.example.permission.myjbm.utils.LoginSharedPreferences;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jbm.jbmsupplier.util.ICtrl;
import com.jbm.jbmsupplier.util.IInformationCtrl;
import com.jbm.jbmsupplier.util.InfomationEntity;
import com.jbm.jbmsupplier.util.enums.ClickTimesType;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.jbm.jbmsupplier.util.abstracts.SendMessageInterfase.gSocket;


/**
 * Created by JBMhaier on 2017/1/17.
 */
// mPullRefreshListView.onRefreshComplete();  完成刷新



public class MyFragment extends BaseFgm {
    private PullToRefreshListView mPullRefreshListView;
    private MyFragmentAdapter adapter;
//    private int screenHeight,screenWidth;
    //类型 例如:热销 互助...
    public static int flag,address;
    SimpleDateFormat df;
    //联网类
    private ReleaseNet net;
    //页数
    private int page=0;

   private ICtrl info;
    private static boolean isVisibleToUser1;
    private List<InfomationEntity>  data1;
    //默认图
    private ImageView lv_default;
    //pull的预加载
    private static boolean isLoad;


    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                //首页数据
                case ReleaseNet.HOMELISTERROR:
                    IInformationCtrl arr= (IInformationCtrl) msg.obj;
                    if(arr.back==false){
                        noNet();
                        return;
                    }
                    List<InfomationEntity>  date=arr.infomationList;
//                       Log.e("main","执行了"+arr.back+"    "+arr.errorinfo+"    服务器返回的数量"+date.size());
//                    praiseList; // 点赞列表
//                    focusList; //收藏列表

                    if(date==null){
                        return;
                    }

                    //是否登录
                    if(sp.getLoginState()== true){
                        //判断当前用户是否收藏
                        for(int i=0;i<date.size();i++){
                            model.modifyDate(date.get(i),df);
                            for(int j=0;j<date.get(i).getFocusList().size();j++){
                                if(gSocket.login_id==date.get(i).getFocusList().get(j).getLoginId()){
                                    date.get(i).setCollect(true);
                                }
                            }
                            //判断当前用户是否点赞
                            for(int j=0;j<date.get(i).getPraiseList().size();j++){
                                if(gSocket.login_id==date.get(i).getPraiseList().get(j).getLoginId()){
                                    date.get(i).setAttention(true);
                                }
                            }
                        }
                        //处理时间

                    }else{
                        for(int i=0;i<date.size();i++){
                            model.modifyDate(date.get(i),df);
                        }

                    }
                    if(page==0){
                        data1.clear();
                        data1.addAll(date);
                        if(data1.size()==0){
                            lv_default.setVisibility(View.VISIBLE);
                        }else{
                            lv_default.setVisibility(View.GONE);
                        }
                        adapter = new MyFragmentAdapter(data1, getActivity(),false);
                        mPullRefreshListView.setAdapter(adapter);
                        huidiao();
                        initListener();
                    }else{
                        if(date.size()!=0){
                            data1.addAll(date);
                            adapter.setNotify(data1);
                            if(flag==0){
                                //缓存
                                DataCache.getInstance(getActivity()).addCache(data1);
                            }
                        }else{
                            //关闭预加载
                            isLoad=true;
                            ILoadingLayout startLabels = mPullRefreshListView
                                    .getLoadingLayoutProxy();
                            startLabels.setRefreshingLabel("您已到底");// 刷新时
                        }
                    }

                    //代表超时
                    if (arr.equals("time out")){
                        lv_default.setVisibility(View.VISIBLE);
                     }
                    mPullRefreshListView.onRefreshComplete();
                    break;
                //收藏回调
                case ReleaseNet.SHOUCANGERROR:
                    info=(ICtrl)msg.obj;
                    loader.setTextstr(info.errorinfo);
                    adapter.netBack(info.back,"shoucang");
                    net.setLog(ClickTimesType.info.toValue(),infoid1, Identifying.getFLG(getActivity()));
                    loader.dismiss();
                    break;
                //点赞回掉
                case ReleaseNet.LICKERROR:
                    info=(ICtrl)msg.obj;
                    loader.setTextstr(info.errorinfo);
                    adapter.netBack(info.back,"dianzan");
                    net.setLog(ClickTimesType.info.toValue(),infoid1, Identifying.getFLG(getActivity()));
                    loader.dismiss();
                    break;

            }
        }
    };

        private LoginSharedPreferences sp;
    private DialogLoading loader;
    private MyFragmentModel model;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View  view = View.inflate(getActivity(), R.layout.fgt_main, null);
        Log.e("main","执行了 onCreateView");
        initData();
      //  loader.show();

        init(view);
        
        return view;
    }



    //当前无网络时执行
    protected void noNet() {
        if(flag==0) {
            if (DataCache.getInstance(getActivity()).getCache() != null) {
                adapter = new MyFragmentAdapter(DataCache.getInstance(getActivity()).getCache(), getActivity(),true);
                mPullRefreshListView.setAdapter(adapter);
            //    lv_default.setVisibility(View.GONE);
            }else{
                lv_default.setVisibility(View.VISIBLE);
            }
        }else{
            lv_default.setVisibility(View.VISIBLE);
        }
    }

    //初始化数据
    private void initData() {
        page=0;
        data1=new ArrayList<InfomationEntity>();
        loader=new DialogLoading(getActivity());
        sp=new LoginSharedPreferences(getActivity());
        //联网的类
        net = new ReleaseNet(handler);
        df = new SimpleDateFormat("yyyy-MM-dd-HH-mm",Locale.CHINA);
        model=new MyFragmentModel();
    }
    //这个是log用
    private int infoid1;
    //回调接口
    private void huidiao() {
        if(adapter==null){
            return ;
        }
        adapter.setRequestOption(new MyFragmentAdapter.RequestOption() {
            @Override
            public void dianzan(int infoid, int loginid, int praiseType) {
                loader.show();
                net.like(infoid,loginid,praiseType);
                infoid1=infoid;
            }

            @Override
            public void shoucang(int infoid, int loginid, int praiseType) {
                loader.show();
                net.collect(infoid,loginid,praiseType);
                infoid1=infoid;
            }
        });
    }
    //初始化监听
    private void initListener() {
        mPullRefreshListView
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>()
                {
                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<ListView> refreshView)
                    {
                        //这里写下拉刷新的任务
                        page=0;
                     //   Log.e("main","下拉时数据  "+MyFragment.this.flag+"    "+address+"    "+page);
                        net.getMessageList(1, MyFragment.this.flag, address, page);//MyFragment.this.flag

                    }

                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<ListView> refreshView)
                    {

                        page+=5;
                        net.getMessageList(1, MyFragment.this.flag,address, page);//MyFragment.this.flag
                        //这里写上拉加载更多的任务

                    }
                });
        mPullRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if(isLoad==false) {
                    page += 5;
                    net.getMessageList(1, MyFragment.this.flag, address, page);//MyFragment.this.flag


                }
            }
        });
        if(MyFragment.this.flag==0){
            mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    net.setLog(ClickTimesType.info.toValue(),data1.get(position).getInfoId(), Identifying.getFLG(getActivity()));

                    if(position==0){
                        if (sp.getLoginState() != true) {
                            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                            return;
                        }
                        startActivity(new Intent(getActivity(), MyAddRessRepair.class));
                    }
                }
            });
        }


    }

    /**
     * 初始化数据
     * @param view
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void init(View view) {
        mPullRefreshListView = (PullToRefreshListView)view. findViewById(R.id.pull_refresh_list);
        lv_default=(ImageView)view.findViewById(R.id.lv_default);
    }
    //外层调用
    public void setType(int type1,int address){
        MyFragment.this.flag=type1;
        MyFragment. this.address=address;
        page=0;
            if (isVisibleToUser1 == true) {
                if(!isNetworkConnected()){
                    noNet();
                    return;
                }
                net.getMessageList(1, MyFragment.this.flag,address, 0);//MyFragment.this.flag

            }else{
                Log.e("main","没有执行请求数据");
            }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisibleToUser1=isVisibleToUser;
        isLoad=false;
    }
}
